<?php
/**
 *  内容栏目控制器
 */
namespace app\admin\controller;
use app\admin\model\ContentSort as ContentSortModel;
use app\admin\model\ModelM as ModelMModel;
class Sorttype extends Common
{
	private $count;

    private $blank;

    private $outData = array();

    private $model;
	private $models;
    public function _initialize()
    {
		parent::_initialize();
        $this->model = new ContentSortModel();
		// 模板文件自动读取模式
		//$tpl=file_list(ROOT_PATH.'app'.DS. current($this->tpl_dir) . DS . $this->model->getTheme());
		//数据读取模式
		$this->models=new ModelMModel();
		$tpl=$this->models->getSelectAll();
        $this->assign('tpls',$tpl);
    }
    // 内容栏目列表
    public function index()
    {
        $this->assign('list', true);
        $tree = $this->model->getList();		
        $sorts = $this->makeSortList($tree);
        $this->assign('sorts', $sorts);
        // 内容模型
		$models=new ModelMModel();
        $this->assign('allmodels', $models->getSelectAll());
        $this->assign('models', $models->getSelect());

        // 内容栏目下拉表
        $sort_tree = $this->model->getSelect();
        $sort_select = $this->makeSortSelect($sort_tree);

        $this->assign('sort_select', $sort_select);

		return $this->fetch();
    }
    // 生成无限级内容栏目列表
    private function makeSortList($tree)
    {
        // 循环生成
        foreach ($tree as $value) {
            $this->count ++;
            $this->outData[$this->count] = new \stdClass();
            $this->outData[$this->count]->id = $value['id'];
            $this->outData[$this->count]->blank = $this->blank;
            $this->outData[$this->count]->name = $value['name'];
            $this->outData[$this->count]->subname = $value['subname'];
            $this->outData[$this->count]->scode = $value['scode'];
            $this->outData[$this->count]->pcode = $value['pcode'];
			$this->outData[$this->count]->lkcode = $value['lkcode'];
            $this->outData[$this->count]->mcode = $value['mcode'];
            $this->outData[$this->count]->listtpl = $value['listtpl'];
            $this->outData[$this->count]->contenttpl = $value['contenttpl'];
            $this->outData[$this->count]->ico = $value['ico'];
            $this->outData[$this->count]->pic = $value['pic'];
            $this->outData[$this->count]->keywords = $value['keywords'];
            $this->outData[$this->count]->description = $value['description'];
            $this->outData[$this->count]->outlink = $value['outlink'];
            $this->outData[$this->count]->sorting = $value['sorting'];
            $this->outData[$this->count]->status = $value['status'];
            $this->outData[$this->count]->filename = $value['filename'];
            $this->outData[$this->count]->type = $value['type'];
            $this->outData[$this->count]->urlname = $value['urlname'];
            $this->outData[$this->count]->create_user = $value['create_user'];
            $this->outData[$this->count]->update_user = $value['update_user'];
            $this->outData[$this->count]->create_time = intval($value['create_time']);
            $this->outData[$this->count]->update_time = intval($value['update_time']);
            if ($value['son']) {
                $this->outData[$this->count]->son = true;
            } else {
                $this->outData[$this->count]->son = false;
            }

            // 子菜单处理
            if ($value['son']) {
                $this->blank .= '　　';
                $this->makeSortList($value['son']);
            }
        }

        // 循环完后回归缩进位置
        $this->blank = substr($this->blank, 6);
        return $this->outData;
    }

    // 内容栏目增加
    public function add()
    {
        $UrlParam=input();
		if($this->request->isPost()){
			$multiplename = trim(input('multiplename'));
            if ($multiplename) {
                $multiplename = str_replace('，', ',', $multiplename);
                $pcode = $UrlParam['pcode'];
                $type = $UrlParam['type'];
                $mcode = $UrlParam['mcode'];
                $listtpl = basename($UrlParam['listtpl']);
                $contenttpl = basename($UrlParam['contenttpl']);
                $status = $UrlParam['status'];
				$outlink=false;

                if (! $pcode) { // 父编码默认为0
                    $pcode = 0;
                }

                if (! $mcode) {
                    alert('栏目模型必须选择！','back');
                }

                if (! $type) {
                    alert('栏目类型不能为空！','back');
                }

                $names = explode(',', $multiplename);
                $lastcode = $this->model->getLastCode();
                $scode = get_auto_code($lastcode);
                foreach ($names as $key => $value) {
				
                    $data[]= array(
                        'acode' => 'cn',
                        'pcode' => $pcode,
                        'scode' => $scode,
                        'name' => $value,
                        'mcode' => $mcode,
                        'listtpl' => $listtpl,
                        'contenttpl' => $contenttpl,
                        'status' => $status,
                        'subname' => '',
                        'filename' => '',
                        'outlink' => '',
                        'ico' => '',
						'faico' => '',
                        'pic' => '',
                        'title' => '',
                        'keywords' => '',
                        'description' => '',
                        'sorting' => 255,
						'create_time' => date('Y-m-d H:i:s',time()),
						'update_time' => date('Y-m-d H:i:s',time()),
                        'create_user' => session('username'),
                        'update_user' => session('username')
                    );
                    $scode = get_auto_code($scode);
                }
				$ContentSortModel=new ContentSortModel();
				// 执行添加
				if ($ContentSortModel->addSortall($data)) {
					if ($type == 1 && !$outlink) { // 在填写了外链时不生成单页
						if ($multiplename) {
							foreach ($data as $key => $value) {
								$this->addSingle($value['scode'], $value['name']);
							}
						} else {
							$this->addSingle($scode, $name);
						}
					}
					$this->success('新增成功！', url('/Sorttype/index'));
				} else {
					$this->error('新增失败！');
				}

            } else {
                // 获取数据
                $scode = get_auto_code($this->model->getLastCode()); // 自动编码;
                $pcode = $UrlParam['pcode'];
                $name = $UrlParam['name'];
                $type = $UrlParam['type'];
                $mcode = $UrlParam['mcode'];
                $listtpl = basename($UrlParam['listtpl']);
                $contenttpl = basename($UrlParam['contenttpl']);
                $status = $UrlParam['status'];
                $subname = $UrlParam['subname'];
                $filename = $UrlParam['filename'];
                $outlink = $UrlParam['outlink'];
                $ico = $UrlParam['ico'];
				$faico = $UrlParam['faico'];
                $pic = $UrlParam['pic'];
                $title = $UrlParam['title'];
                $keywords = $UrlParam['keywords'];
                $description = $UrlParam['description'];

                if (! $scode) {
                    alert('编码不能为空！','back');
                }

                if (! $pcode) { // 父编码默认为0
                    $pcode = 0;
                }

                if (! $name) {
                    alert('栏目名不能为空！','back');
                }

                if (! $mcode) {
                    alert('栏目模型必须选择！','back');
                }

				
				/*$mcode_check=$this->model->checkSort("mcode='$mcode'");
				if ($pcode==0 && $mcode_check) { // 父编码默认为0
					$modelm=new ModelMModel();
					$modelname=$modelm->getName($UrlParam['mcode']);
					//echo $modelm->getlastsql();
                    alert(''.$modelname.'编码已存在不能作为顶级栏目，请添加为'.$modelname.'下级!','back');
                }*/

                if (! $type) {
                    alert('栏目类型不能为空！','back');
                }

                if ($filename && ! preg_match('/^[a-zA-Z0-9\-]+$/', $filename)) {
                    alert('URL名称只允许字母、数字、横线组成!','back');
                }

                if ($filename && $this->model->checkUrlname($filename)) {
                    alert('URL名称与模型URL名称冲突，请换一个名称！','back');
                }

                // 检查编码
                if ($this->model->checkSort("scode='$scode'")) {
                    alert('该内容栏目编号已经存在，不能再使用！','back');
                }
                // 构建数据
                $data = array(
                    'acode' => 'cn',
                    'pcode' => $pcode,
                    'scode' => $scode,
                    'name' => $name,
                    'mcode' => $mcode,
                    'listtpl' => $listtpl,
                    'contenttpl' => $contenttpl,
                    'status' => $status,
                    'subname' => $subname,
                    'filename' => $filename,
                    'outlink' => $outlink,
                    'ico' => $ico,
					'faico' => $faico,
                    'pic' => $pic,
                    'title' => $title,
                    'keywords' => $keywords,
                    'description' => $description,
                    'sorting' => 255,
					'create_time' => date('Y-m-d H:i:s',time()),
					'update_time' => date('Y-m-d H:i:s',time()),
                    'create_user' => session('username'),
                    'update_user' => session('username')
                );
				$ContentSortModel=new ContentSortModel();
				// 执行添加
				if ($ContentSortModel->addSort($data)) {
					if ($type == 1 && !$outlink) { // 在填写了外链时不生成单页
						if ($multiplename) {
							foreach ($data as $key => $value) {
								$this->addSingle($value['scode'], $value['name']);
							}
						} else {
							$this->addSingle($scode, $name);
						}
					}
					$this->success('新增成功！', url('/Sorttype/index'));
				} else {
					$this->error('新增失败！');
				}
            }
			
        } else {
            $this->assign('add', true);
            // 内容栏目下拉表
            $sort_tree = $this->model->getSelect();
            $sort_select = $this->makeSortSelect($sort_tree);
            $this->assign('sort_select', $sort_select);
            // 内容模型
			$models=new ModelMModel();
            $this->assign('models', $models->getSelect());
			return $this->fetch("contentsort");
        }
    }

    // 生成内容栏目下拉选择
	private function makeSortSelect($tree, $selectid = null)
    {
        $list_html = '';
        foreach ($tree as $value) {
            // 默认选择项
            if ($selectid == $value->scode) {
                $select = "selected='selected'";
            } else {
                $select = '';
            }
            $list_html .= "<option value=".$value->scode." ".$select.">".$this->blank.$value->name."";
            // 子菜单处理
            if ($value->son) {
                $this->blank .= '　　';
                $list_html .= $this->makeSortSelect($value->son, $selectid);
            }
        }
        // 循环完后回归位置
        $this->blank = substr($this->blank, 0, - 6);
        return $list_html;
    }


	// 内容栏目删除
    public function del()
    {
		$UrlParam=input();
        // 执行批量删除
         if($this->request->isPost()) {
			 //$list = input('post.list/a');
			 $list = $UrlParam['list'];
            if ($list) {
                if ($this->model->delSortList($list)) {
                    $this->success('批量删除成功！');
                } else {
                    $this->error('批量删除失败！');
                }
            } else {
                alert('请选择要删除的栏目！','back');
            }
        }

        if (! $scode = input('scode')) {
            $this->error('传递的参数值错误！');
        }
        if ($this->model->delSort($scode)) {
            $this->success('删除成功！');
        } else {
            $this->error('删除失败！');
        }
    }

    // 内容栏目修改
    public function mod()
    {
		$UrlParam=array();
		$UrlParam=input();
		$submit=input('submit');

        if ($submit) {

            switch ($submit) {
                case 'sorting': // 修改列表排序
                    $listall = input('post.listall/a');
                    if ($listall) {
                        $sorting = input('post.sorting/a');
                        foreach ($listall as $key => $value) {
                            if ($sorting[$key] === '' || ! is_numeric($sorting[$key]))
                                $sorting[$key] = 255;
								$strongdata['sorting']=$sorting[$key];
                            $this->model->modSortSorting($value, $strongdata);
                        }
                        $this->success('修改成功！');
                    } else {
                        $this->error('排序失败，无任何内容！');
                    }
                    break;
            }
        }
        if (! $scode = input('scode')) {
             $this->error('传递的参数值错误！');
        }
        // 单独修改状态
        if (($field = input('field')) && ! is_null($value = input('value'))) {
			$info[$field]=$value;
			$info['update_user']= session('username');
            if ($this->model->modSort($scode,$info)) {
                location(- 1);
            } else {
                alert('修改失败！','back');
            }
        }

        // 修改操作
        if ($this->request->isPost()) {
            // 获取数据
            $pcode = $UrlParam['pcode'];
			$lkcode = $UrlParam['lkcode'];
            $name = $UrlParam['name'];
            $mcode = $UrlParam['mcode'];
            $type = $UrlParam['type'];
            $listtpl = basename($UrlParam['listtpl']);
            $contenttpl = basename($UrlParam['contenttpl']);
            $status = $UrlParam['status'];
            $subname = $UrlParam['subname'];
            $filename = $UrlParam['filename'];
            $outlink = $UrlParam['outlink'];
            $ico = $UrlParam['ico'];
			$faico = $UrlParam['faico'];
            $pic = $UrlParam['pic'];
            $title = $UrlParam['title'];
            $keywords = $UrlParam['keywords'];
            $description = $UrlParam['description'];
            $modsub = $UrlParam['modsub'];

            if (! $pcode) { // 父编码默认为0
                $pcode = 0;
            }
			if (! $lkcode) { //关联栏目默认为0
                $lkcode = 0;
            }
            if (! $name) {
                alert('栏目名不能为空！','back');
            }

            if (! $mcode) {
                alert('栏目模型必须选择！','back');
            }

            if (! $type) {
                alert('栏目类型不能为空！','back');
            }

            if ($filename && ! preg_match('/^[a-zA-Z0-9\-]+$/', $filename)) {
                alert('URL名称只允许字母、数字、横线组成!','back');
            }

            if ($filename && $this->model->checkUrlname($filename)) {
                alert('URL名称与模型URL名称冲突，请换一个名称！','back');
            }
            if ($filename) {
                while ($this->model->checkFilename($filename, "scode<>'$scode'")) {
                    $filename = $filename . '-' . mt_rand(1, 20);
                }
            }

            // 构建数据
            $data = array(
                'pcode' => $pcode,
				'lkcode' => $lkcode,
                'name' => $name,
                'mcode' => $mcode,
                'listtpl' => $listtpl,
                'contenttpl' => $contenttpl,
                'status' => $status,
                'subname' => $subname,
                'filename' => $filename,
                'outlink' => $outlink,
                'ico' => $ico,
				'faico' => $faico,
                'pic' => $pic,
                'title' => $title,
                'keywords' => $keywords,
                'description' => $description,
                'update_user' => session('username')
            );

            // 执行添加
            if ($this->model->modSort($scode, $data, $modsub)) {
                // 如果修改为单页并且跳转，则删除单页内容，否则判断是否存在内容，不存在则添加
                if ($type == 1 && $outlink) {
                    $this->model->delContent($scode);
                } elseif ($type == 1 && ! $this->model->findContent($scode)) {
                    $this->addSingle($scode, $name);
                }

                $this->success('修改成功！', url('/Sorttype/index'));
            } else {
                location(- 1);
            }
        } else { // 调取修改内容
            $this->assign('mod', true);

            $sort = $this->model->getSort($scode);
            if (! $sort) {
                $this->error('编辑的内容已经不存在！');
            }
            $this->assign('sort', $sort);

            // 父编码下拉选择
            $sort_tree = $this->model->getSelect();
            $sort_select = $this->makeSortSelect($sort_tree, $sort->pcode);
            $this->assign('sort_select', $sort_select);


			$lk_list = $this->model->getLklist();
			$this->assign('lk_list', $lk_list);

            // 内容模型
			$models=new ModelMModel();
            $this->assign('models', $models->getSelect());
			$this->assign('UrlParam', $UrlParam);
			return $this->fetch();
        }
    }

    // 添加栏目时执行单页内容增加
    public function addSingle($scode, $title)
    {
        // 构建数据
        $data = array(
            'acode' => 'cn',
            'scode' => $scode,
            'subscode' => '',
            'title' => $title,
            'titlecolor' => '#333333',
            'subtitle' => '',
            'filename' => '',
            'author' => session('username'),
            'source' => '本站',
            'outlink' => '',
            'date' => date('Y-m-d H:i:s'),
            'ico' => '',
            'pics' => '',
            'content' => '',
            'tags' => '',
            'enclosure' => '',
            'keywords' => '',
            'description' => '',
            'sorting' => 255,
            'status' => 1,
            'istop' => 0,
            'isrecommend' => 0,
            'isheadline' => 0,
            'visits' => 0,
            'likes' => 0,
            'oppose' => 0,
			'create_time' => date('Y-m-d H:i:s',time()),
			'update_time' => date('Y-m-d H:i:s',time()),
            'create_user' => session('username'),
            'update_user' => session('username')
        );
        // 执行添加
        if ($this->model->addSingle($data)) {
            return true;
        } else {
            return false;
        }
    }
}
